<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UsersController extends AppController {

    public $helpers = array('Html', 'Form');

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect(array('controller' => 'accounts', 'action' => 'index'));
            } else {
                $this->Session->setFlash(__('Invalid email or password, try again'));
            }
        }
    }

    public function beforeFilter() {
        parent::beforeFilter();
    }

    function logout() {
        $this->Session->setFlash('You have successfully logged out.');
        $this->redirect($this->Auth->logout());
    }

    public function addUser() {
        if ($this->request->is('post')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('Registration successful,Please login');
                $this->redirect(array('action' => 'login'));
            } else {
                $this->Session->setFlash('The user could not be saved. Please, try again.');
            }
        }
    }
	

    public function isAuthorized($user) {
        parent::isAuthorized($user);
        if ($this->action == 'add') {
            return true;
        }
    }
	
	public function changePassword() {
        
        if ($this->request->data) {

                $this->request->data['User']['email'] = $this->Auth->User('email');
                $email = $this->Auth->User('email');
                $pwd = $this->request->data['User']['new password'];
                $pwdRep = $this->request->data['User']['confirm new password'];
                $hashedPwd = AuthComponent::password($pwd);

                if (strlen($pwd) < 8){
                    $this->Session->setFlash('Your password must be at least 8 characters');
                }
                else if($pwd != $pwdRep) {
                    $this->Session->setFlash('Your passwords do not match');
                }

                else {
                    
                    //debug($this->User->email);
                    if($this->User->updateAll(array('User.password' => "'".$hashedPwd."'") , array('User.email' => $email))){
                        $this->Session->setFlash('Password successfully updated !');
                        $this->Redirect('/');
                    }
                    else{
                    $this->Session->setFlash('A problem occured ... you password was not changed');
                    }

                }    
            }
    }
	

}

?>
